package org.misty.seckill.controller;

import org.misty.seckill.model.User;
import org.misty.seckill.redis.RedisService;
import org.misty.seckill.redis.UserKey;
import org.misty.seckill.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
  @Autowired
  private UserService userService;
  @Autowired
  private RedisService redisService;

  @GetMapping("/{id:\\d+}")
  public User byId(@PathVariable int id) {
    System.out.println("find user");
    return this.userService.getById(id);
  }

  @GetMapping("/cache/{id:\\d+}")
  public boolean cacheUser(@PathVariable int id) {
    var user = this.userService.getById(id);
    return this.redisService.set(UserKey.ID, "" + user.getId(), user);
  }

  @GetMapping("/hint/{id:\\d+}")
  public User hintUser(@PathVariable int id) {
    return this.redisService.get(UserKey.ID, "" + id, User.class);
  }

  @GetMapping("/info")
  public User info(@RequestAttribute(value = "user") User user) {
    return user;
  }
}
